package com.itboye.jigongbao.base

import android.annotation.TargetApi
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.FragmentActivity
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.view.View
import android.view.WindowManager
import com.itboye.jigongbao.app.MyApplication
import com.itboye.jigongbao.utils.IsNeedClick
import com.itboye.jigongbao.utils.permission.PermissionListener
import com.umeng.analytics.MobclickAgent


abstract class BaseActivity : FragmentActivity(), View.OnClickListener {

    private val PERMISSION_REQUESTCODE = 100
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
        initWindow()
        initData()
        MyApplication.instance!!.addActivity(this)
        MyApplication.instance!!.mPushAgent!!.onAppStart()
    }

    protected abstract fun getLayoutId(): Int

    protected abstract fun initData()
    @TargetApi(19)
    private fun initWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            //            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//Android Lg8.0 虚拟按键会隐藏布局
        }
        smartInject()
    }

    private lateinit var mListener: PermissionListener

    fun requestRunPermisssion(permissions: Array<String>, listener: PermissionListener) {
        mListener = listener
        val permissionLists = ArrayList<String>()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(permission)
            }
        }

        if (!permissionLists.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionLists.toTypedArray(), PERMISSION_REQUESTCODE)
        } else {
            //表示全都授权了
            mListener.onGranted()
        }
    }

    fun showPermission(activity: Activity){
        //当拒绝了授权后，为提升用户体验，可以以弹窗的方式引导用户到设置中去进行设置
        AlertDialog.Builder(activity)
                .setMessage("需要开启权限才能使用此功能")
                .setPositiveButton("设置", DialogInterface.OnClickListener { dialog, which ->
                    //引导用户到设置中去进行设置
                    val intent = Intent()
                    intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                    intent.data = Uri.fromParts("package", packageName, null)
                    startActivity(intent)
                })
                .setNegativeButton("取消", null)
                .create()
                .show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            PERMISSION_REQUESTCODE -> if (grantResults.size > 0) {
                //存放没授权的权限
                val deniedPermissions = ArrayList<String>()
                for (i in grantResults.indices) {
                    val grantResult = grantResults[i]
                    val permission = permissions[i]
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        deniedPermissions.add(permission)
                    }
                }
                if (deniedPermissions.isEmpty()) {
                    //说明都授权了
                    mListener.onGranted()
                } else {
                    mListener.onDenied(deniedPermissions)
                }
            }
            else -> {
            }
        }
    }

    /**
     * 自动获取控件
     */
    private fun smartInject() {
        try {
            var clz: Class<out Activity> = javaClass

            while (clz != BaseActivity::class.java) {

                val fs = clz.declaredFields
                val res = resources
                val packageName = packageName
                for (field in fs) {
                    if (!View::class.java.isAssignableFrom(field.type)) {
                        continue
                    }
                    val viewId = res.getIdentifier(field.name, "id",
                            packageName)
                    if (viewId == 0)
                        continue
                    field.isAccessible = true
                    try {
                        val v = findViewById<View>(viewId)
                        field.set(this, v)
                        val c = field.type
                        //判断是否有注解
                        if (field.annotations != null) {
                            if (field.isAnnotationPresent(IsNeedClick::class.java)) {//如果属于这个注解
                                //为这个控件设置属性
                                field.isAccessible = true//允许修改反射属性
                                val inject = field.getAnnotation(IsNeedClick::class.java)
                                //                                int value=inject.value();//得到注解的值
                                //                                if(value==-1){
                                //
                                //                                }
                            } else {
                                val m = c.getMethod("setOnClickListener",
                                        View.OnClickListener::class.java)
                                m.invoke(v, this)
                            }
                        } else {
                            //                            Method m = c.getMethod("setOnClickListener",
                            //                                    View.OnClickListener.class);
                            //                            m.invoke(v, this);
                        }
                    } catch (e: Throwable) {
                    }

                    field.isAccessible = false

                }

                clz = clz.superclass as Class<out Activity>

            }
        } catch (e: Exception) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }

    }

    override fun onResume() {
        // TODO Auto-generated method stub
        super.onResume()
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        // TODO Auto-generated method stub
        super.onPause()
        MobclickAgent.onPause(this)
    }


    /**
     * 获取状态栏高度
     *
     * @return
     */
    fun getStatusBarHeight(): Int {
        //获取status_bar_height资源的ID
        val resourceId = getResources()?.getIdentifier("status_bar_height", "dimen", "android")
        return if (resourceId!! > 0) {
            //根据资源ID获取响应的尺寸值
            getResources()!!.getDimensionPixelSize(resourceId)
        } else 0
    }
}
